package com.qxzn.module.smarthome.fragment;

import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.qxzn.app.bean.BaseBean;
import com.qxzn.app.bean.TuyaTokenBean;
import com.qxzn.app.bean.TuyaUidBean;
import com.qxzn.app.page.BaseFragment;
import com.qxzn.app.page.interfaces.MyInterface;
import com.qxzn.app.page.model.SmartHomeModel;
import com.qxzn.app.page.view.MyDialog;
import com.qxzn.app.util.AppUtil;
import com.qxzn.app.util.SharePreferenceUtil;
import com.qxzn.module.jwebsocket.JWebSocketClient;
import com.qxzn.module.jwebsocket.JWebSocketClientService;
import com.qxzn.module.smarthome.R;
import com.qxzn.module.smarthome.R2;
import com.tuya.smart.android.common.utils.WiFiUtil;
import com.tuya.smart.android.user.api.ILoginCallback;
import com.tuya.smart.android.user.bean.User;
import com.tuya.smart.home.sdk.TuyaHomeSdk;
import com.tuya.smart.home.sdk.builder.ActivatorBuilder;
import com.tuya.smart.sdk.api.ITuyaActivator;
import com.tuya.smart.sdk.api.ITuyaSmartActivatorListener;
import com.tuya.smart.sdk.bean.DeviceBean;
import com.tuya.smart.sdk.enums.ActivatorModelEnum;

import butterknife.BindView;

/**
 * 智能家居页面
 */
public class SmartHomeFragment extends BaseFragment implements MyInterface.GetTuyaUidListener, MyInterface.GetTuyaTokenListener, MyInterface.NotifyServerListener {

    @BindView(R2.id.textView)
    TextView textView;
    @BindView(R2.id.editText)
    EditText editText;
    private SmartHomeModel smartHomeModel;
    private ITuyaActivator mTuyaActivator;
    private String deviceId;
    private JWebSocketClientService.JWebSocketClientBinder binder;
    private JWebSocketClientService jWebSClientService;
    private JWebSocketClient client;
    private ChatMessageReceiver chatMessageReceiver;
    private boolean isServiceConne;
    private ServiceConnection serviceConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
            Log.e("MainActivity", "服务与活动成功绑定");
            binder = (JWebSocketClientService.JWebSocketClientBinder) iBinder;
            jWebSClientService = binder.getService();
            client = jWebSClientService.client;
//            if (jWebSClientService != null) {
//                jWebSClientService.sendMsg("{\"type\":\"1\",\"username\":\"15134552845\",\"userpwd\":\"qxzn6688\"}\n");
//            }
        }

        @Override
        public void onServiceDisconnected(ComponentName componentName) {
            Log.e("MainActivity", "服务与活动成功断开");
        }
    };

    @Override
    protected int initLayout() {
        return R.layout.fragment_smart_home;
    }

    @Override
    protected void initView() {
//        textView.setText(getArguments().getString("title"));
    }

    @Override
    protected void initData(Bundle savedInstanceState) {
        smartHomeModel = new SmartHomeModel(getActivity());
        smartHomeModel.setGetTuyaUidListener(this);
        smartHomeModel.setGetTuyaTokenListener(this);
        smartHomeModel.setNotifyServerListener(this);
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                smartHomeModel.getTuyaUid(new JSONObject());
                smartHomeModel.getTuyaToken(new JSONObject());
            }
        }, 2000);
        editText.setText("qxzn666888");
        textView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (TextUtils.isEmpty(SharePreferenceUtil.getDeviceId(getActivity()))) {
                    AppUtil.showToast(getActivity(), "请先扫码获取机器码");
                    return;
                }
                if (TextUtils.isEmpty(editText.getText().toString().trim())) {
                    AppUtil.showToast(getActivity(), editText.getHint().toString());
                    return;
                }
                if (mTuyaActivator != null) {
                    AppUtil.showLog("开始配网\n机器码：" + SharePreferenceUtil.getDeviceId(getActivity()) +
                            "\nWIFI名称：" + WiFiUtil.getCurrentSSID(getActivity()) + "\nWIFI密码：" + editText.getText().toString().trim() +
                            "\nUID：" + SharePreferenceUtil.getTuyaUid(getActivity()) + "\nTOKEN：" + SharePreferenceUtil.getTuyaToken(getActivity()));

                    new MyDialog.Builder(getActivity()).setMessage("开始配网\n机器码：" + SharePreferenceUtil.getDeviceId(getActivity()) +
                            "\nWIFI名称：" + WiFiUtil.getCurrentSSID(getActivity()) + "\nWIFI密码：" + editText.getText().toString().trim() +
                            "\nUID：" + SharePreferenceUtil.getTuyaUid(getActivity()) + "\nTOKEN：" + SharePreferenceUtil.getTuyaToken(getActivity())).create().show();
                    mTuyaActivator.start(); //开始配网
                } else {
                    loginTuya();
                }
            }
        });
//        initSocket();
    }

    private void loginTuya() {
        AppUtil.showLog(SharePreferenceUtil.getTuyaUid(getActivity()));
        AppUtil.showLog(SharePreferenceUtil.getUserName(getActivity()));
        AppUtil.showLog(SharePreferenceUtil.getPwd(getActivity()));
        //手机密码登陆
        TuyaHomeSdk.getUserInstance().loginWithPhonePassword("86", SharePreferenceUtil.getUserName(getActivity()), SharePreferenceUtil.getPwd(getActivity()), new ILoginCallback() {
            @Override
            public void onSuccess(User user) {
                AppUtil.showToast(getActivity(), "登录成功，用户名：" + JSON.toJSONString(user));
                AppUtil.showLog("登录成功，用户名：" + JSON.toJSONString(user));
                initApConfig();
            }

            @Override
            public void onError(String code, String error) {
                AppUtil.showToast(getActivity(), "登录失败：" + "code: " + code + "，error:" + error);
                AppUtil.showLog("登录失败：" + "code: " + code + "，error:" + error);
            }
        });
//        //uid登陆、ay1566541194894jVRB3
//        TuyaHomeSdk.getUserInstance().loginWithUid("86", SharePreferenceUtil.getTuyaUid(getActivity()), MD5Utils.MD5(SharePreferenceUtil.getPwd(getActivity())), new ILoginCallback() {
//            @Override
//            public void onSuccess(User user) {
//                AppUtil.showLog("登录成功，用户名：" + JSON.toJSONString(user));
//                initApConfig();
//            }
//
//            @Override
//            public void onError(String code, String error) {
//                AppUtil.showLog("登录失败：" + "code: " + code + "，error:" + error);
//            }
//        });
    }

    /**
     * 初始化配网参数
     */
    private void initApConfig() {
        mTuyaActivator = TuyaHomeSdk.getActivatorInstance().newMultiActivator(new ActivatorBuilder()
//        mTuyaActivator = TuyaHomeSdk.getActivatorInstance().newActivator(new ActivatorBuilder()
                .setSsid(WiFiUtil.getCurrentSSID(getActivity()))
                .setContext(getActivity())
                .setPassword(editText.getText().toString().trim())
                .setActivatorModel(ActivatorModelEnum.TY_EZ)
//                .setActivatorModel(ActivatorModelEnum.TY_AP)
//                .setTimeOut(30)
                .setToken(SharePreferenceUtil.getTuyaToken(getActivity()))
                .setListener(new ITuyaSmartActivatorListener() {
                    @Override
                    public void onError(String errorCode, String errorMsg) {
                        new MyDialog.Builder(getActivity()).setMessage("配网错误：" + errorMsg).create().show();
                        AppUtil.showLog("配网错误：" + errorMsg);
                    }

                    @Override
                    public void onActiveSuccess(DeviceBean devResp) {
                        deviceId = devResp.getDevId();
                        new MyDialog.Builder(getActivity()).setMessage("设备配网成功，且设备上线（手机可以直接控制），可以通过：" + JSON.toJSONString(devResp)).create().show();
                        AppUtil.showLog("设备配网成功，且设备上线（手机可以直接控制），可以通过：" + JSON.toJSONString(devResp));
                        JSONObject params = new JSONObject();
                        params.put("code", SharePreferenceUtil.getDeviceId(getActivity()));
                        params.put("device_id", deviceId);
                        smartHomeModel.notifyServer(params);
                    }

                    @Override
                    public void onStep(String step, Object data) {
                        new MyDialog.Builder(getActivity()).setMessage("配网onStep：" + step + "\n" + data).create().show();
                        AppUtil.showLog("配网onStep：" + step + "\n" + data);
                    }
                }));
    }

    private void initSocket() {
        //启动服务
        startJWebSClientService();
        //绑定服务
        bindService();
        //注册广播
        doRegisterReceiver();
    }

    /**
     * 绑定服务
     */
    private void bindService() {
        Intent bindIntent = new Intent(getActivity(), JWebSocketClientService.class);
        isServiceConne = getActivity().bindService(bindIntent, serviceConnection, Context.BIND_AUTO_CREATE);
    }

    /**
     * 启动服务（websocket客户端服务）
     */
    private void startJWebSClientService() {
        Intent intent = new Intent(getActivity(), JWebSocketClientService.class);
        getActivity().startService(intent);
    }

    /**
     * 动态注册广播
     */
    private void doRegisterReceiver() {
        chatMessageReceiver = new ChatMessageReceiver();
        IntentFilter filter = new IntentFilter("com.xch.servicecallback.content");
        getActivity().registerReceiver(chatMessageReceiver, filter);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (smartHomeModel != null) {
            smartHomeModel.removeListener();
        }
        if (mTuyaActivator != null) {
            mTuyaActivator.onDestroy(); //退出页面销毁一些缓存和监听
        }
        if (isServiceConne) {
            getActivity().unbindService(serviceConnection);
        }
        if (chatMessageReceiver != null) {
            getActivity().unregisterReceiver(chatMessageReceiver);
        }
    }

    @Override
    public void onGetTuyaUidSuccess(BaseBean<TuyaUidBean> baseBean) {
        if (baseBean != null && baseBean.getData() != null) {
            SharePreferenceUtil.setTuyaUid(getActivity(), baseBean.getData().getUid());
//            loginTuya();
        }
    }

    @Override
    public void onGetTuyaUidFailure() {

    }

    @Override
    public void onGetTuyaTokenSuccess(BaseBean<TuyaTokenBean> baseBean) {
        if (baseBean != null && baseBean.getData() != null) {
            SharePreferenceUtil.setTuyaToken(getActivity(), baseBean.getData().getRegion() + baseBean.getData().getToken() + baseBean.getData().getSecret());
        }
    }

    @Override
    public void onGetTuyaTokenFailure() {

    }

    @Override
    public void onNotifyServerSuccess(BaseBean<TuyaTokenBean> baseBean) {
        new MyDialog.Builder(getActivity()).setMessage("请求结果：" + JSON.toJSONString(baseBean)).create().show();
    }

    @Override
    public void onNotifyServerFailure() {
        new MyDialog.Builder(getActivity()).setMessage("请求结果：网络错误").create().show();
    }

    private class ChatMessageReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            String message = intent.getStringExtra("message");
        }
    }
}
